from PyQt6.QtWidgets import (
    QWidget, QTabWidget, QTableWidget, QTextEdit, QVBoxLayout,
    QHBoxLayout, QToolBar,  QHeaderView, QAbstractItemView,
    QLineEdit, QPushButton, QComboBox, QLabel, QMessageBox
)
from PyQt6.QtGui import QAction, QIcon, QKeySequence
from PyQt6.QtCore import Qt, QTimer
import pandas as pd
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from core.query_engine import QueryEngine
from utils.logger import get_logger

logger = get_logger(__name__)

class DataViewer(QWidget):
    def __init__(self, table_info=None, parent=None):
        super().__init__(parent)
        self.table_info = table_info
        self.data = None
        self.current_page = 1
        self.page_size = 100
        self.total_rows = 0

        # 创建布局
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # 创建工具栏
        self.create_toolbar()
        layout.addWidget(self.toolbar)

        # 创建数据标签页
        self.tabs = QTabWidget()
        layout.addWidget(self.tabs)

        # 数据表标签
        self.data_tab = QTableWidget()
        self.data_tab.setEditTriggers(QTableWidget.EditTrigger.DoubleClicked)
        self.data_tab.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.data_tab.setAlternatingRowColors(True)
        self.data_tab.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
        self.data_tab.horizontalHeader().setStretchLastSection(True)
        self.tabs.addTab(self.data_tab, "数据")

        # 文本结果标签
        self.text_tab = QTextEdit()
        self.text_tab.setReadOnly(True)
        self.tabs.addTab(self.text_tab, "信息")

        # 图表标签
        self.chart_tab = QWidget()
        self.chart_layout = QVBoxLayout(self.chart_tab)
        self.chart_layout.setContentsMargins(10, 10, 10, 10)
        self.tabs.addTab(self.chart_tab, "图表")

        # 初始显示文本标签
        self.tabs.setCurrentIndex(1)

        # 创建分页控件
        self.create_pagination()
        layout.addLayout(self.pagination_layout)

        # 如果提供了表信息，加载数据
        if table_info:
            QTimer.singleShot(100, self.load_data)

    def create_toolbar(self):
        self.toolbar = QToolBar("数据工具栏")
        self.toolbar.setIconSize(QSize(20, 20))

        # 刷新按钮
        refresh_action = QAction(QIcon("resources/icons/refresh.png"), "刷新", self)
        refresh_action.triggered.connect(self.load_data)
        self.toolbar.addAction(refresh_action)

        # 新增行按钮
        add_row_action = QAction(QIcon("resources/icons/add_row.png"), "新增行", self)
        add_row_action.triggered.connect(self.add_row)
        self.toolbar.addAction(add_row_action)

        # 删除行按钮
        delete_row_action = QAction(QIcon("resources/icons/delete_row.png"), "删除行", self)
        delete_row_action.triggered.connect(self.delete_selected_rows)
        self.toolbar.addAction(delete_row_action)

        self.toolbar.addSeparator()

        # 提交更改按钮
        commit_action = QAction(QIcon("resources/icons/commit.png"), "提交更改", self)
        commit_action.triggered.connect(self.commit_changes)
        self.toolbar.addAction(commit_action)

        # 撤销更改按钮
        revert_action = QAction(QIcon("resources/icons/revert.png"), "撤销更改", self)
        revert_action.triggered.connect(self.revert_changes)
        self.toolbar.addAction(revert_action)

        self.toolbar.addSeparator()

        # 导出数据按钮
        export_action = QAction(QIcon("resources/icons/export.png"), "导出数据", self)
        export_action.triggered.connect(self.export_data)
        self.toolbar.addAction(export_action)

        # 导入数据按钮
        import_action = QAction(QIcon("resources/icons/import.png"), "导入数据", self)
        import_action.triggered.connect(self.import_data)
        self.toolbar.addAction(import_action)

    def create_pagination(self):
        """创建分页控件"""
        self.pagination_layout = QHBoxLayout()
        self.pagination_layout.setContentsMargins(10, 5, 10, 5)

        # 第一页按钮
        first_page_btn = QPushButton("<<")
        first_page_btn.clicked.connect(lambda: self.set_page(1))
        self.pagination_layout.addWidget(first_page_btn)

        # 上一页按钮
        prev_page_btn = QPushButton("<")
        prev_page_btn.clicked.connect(lambda: self.set_page(max(1, self.current_page - 1)))
        self.pagination_layout.addWidget(prev_page_btn)

        # 页码输入
        self.page_edit = QLineEdit()
        self.page_edit.setFixedWidth(50)
        self.page_edit.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.page_edit.returnPressed.connect(self.on_page_edit_return)
        self.pagination_layout.addWidget(self.page_edit)

        # 总页数标签
        self.total_pages_label = QLabel("/ 1")
        self.pagination_layout.addWidget(self.total_pages_label)

        # 下一页按钮
        next_page_btn = QPushButton(">")
        next_page_btn.clicked.connect(lambda: self.set_page(min(self.total_pages, self.current_page + 1)))
        self.pagination_layout.addWidget(next_page_btn)

        # 最后一页按钮
        last_page_btn = QPushButton(">>")
        last_page_btn.clicked.connect(lambda: self.set_page(self.total_pages))
        self.pagination_layout.addWidget(last_page_btn)

        # 每页行数选择
        self.pagination_layout.addStretch()
        self.pagination_layout.addWidget(QLabel("每页行数:"))

        self.page_size_combo = QComboBox()
        self.page_size_combo.addItems(["50", "100", "200", "500", "1000"])
        self.page_size_combo.setCurrentText("100")
        self.page_size_combo.currentTextChanged.connect(self.change_page_size)
        self.pagination_layout.addWidget(self.page_size_combo)

        # 总行数标签
        self.total_rows_label = QLabel("总行数: 0")
        self.pagination_layout.addWidget(self.total_rows_label)

    def load_data(self):
        """加载表数据"""
        if not self.table_info:
            self.show_message("错误：未选择表")
            return

        try:
            # 获取总行数
            self.total_rows = self.get_total_rows()
            self.total_pages = max(1, (self.total_rows + self.page_size - 1) // self.page_size)

            # 更新分页控件
            self.update_pagination()

            # 执行查询获取当前页数据
            offset = (self.current_page - 1) * self.page_size
            query = f"SELECT * FROM {self.table_info['name']} LIMIT {self.page_size} OFFSET {offset}"

            query_engine = QueryEngine()
            result = query_engine.execute(
                connection=self.table_info["connection"],
                query=query
            )

            if result["type"] == "query":
                self.data = result["data"]
                self.display_data(result["data"], result["columns"])
            else:
                self.show_message(f"获取数据失败: {result.get('message', '未知错误')}")
        except Exception as e:
            self.show_message(f"加载数据错误: {str(e)}")
            logger.error(f"加载数据错误: {str(e)}")

    def get_total_rows(self):
        """获取表的总行数"""
        query = f"SELECT COUNT(*) FROM {self.table_info['name']}"
        query_engine = QueryEngine()
        result = query_engine.execute(
            connection=self.table_info["connection"],
            query=query
        )

        if result["type"] == "query" and result["data"]:
            return result["data"][0][0]
        return 0

    def update_pagination(self):
        """更新分页控件状态"""
        self.page_edit.setText(str(self.current_page))
        self.total_pages_label.setText(f"/ {self.total_pages}")
        self.total_rows_label.setText(f"总行数: {self.total_rows}")

    def set_page(self, page):
        """设置当前页码"""
        if page < 1 or page > self.total_pages:
            return
        self.current_page = page
        self.load_data()

    def change_page_size(self, size):
        """更改每页行数"""
        self.page_size = int(size)
        self.current_page = 1
        self.load_data()

    def on_page_edit_return(self):
        """页码输入框回车事件"""
        try:
            page = int(self.page_edit.text())
            self.set_page(page)
        except ValueError:
            pass

    def display_data(self, data, columns):
        """在表格中显示数据"""
        self.data_tab.clear()
        self.data_tab.setRowCount(len(data))
        self.data_tab.setColumnCount(len(columns))
        self.data_tab.setHorizontalHeaderLabels(columns)

        for row_idx, row in enumerate(data):
            for col_idx, value in enumerate(row):
                self.data_tab.setItem(row_idx, col_idx, QTableWidgetItem(str(value)))

        # 显示在文本标签中
        self.text_tab.clear()
        self.text_tab.append(f"表: {self.table_info['name']}")
        self.text_tab.append(f"总行数: {self.total_rows}")
        self.text_tab.append(f"当前显示: 第 {(self.current_page-1)*self.page_size+1} 到 {min(self.current_page*self.page_size, self.total_rows)} 行")

        # 生成图表
        self.generate_charts(data, columns)

    def generate_charts(self, data, columns):
        """生成数据图表"""
        # 清除之前的图表
        for i in reversed(range(self.chart_layout.count())):
            widget = self.chart_layout.itemAt(i).widget()
            if widget:
                widget.deleteLater()

        # 创建DataFrame
        try:
            df = pd.DataFrame(data, columns=columns)

            # 数值列统计图
            numeric_cols = df.select_dtypes(include='number').columns
            if len(numeric_cols) > 0:
                fig = Figure(figsize=(8, 4))
                canvas = FigureCanvas(fig)
                ax = fig.add_subplot(111)
                df[numeric_cols].hist(ax=ax, bins=15)
                ax.set_title('数值分布')
                self.chart_layout.addWidget(canvas)

            # 类别列统计图
            category_cols = df.select_dtypes(exclude='number').columns
            for col in category_cols[:3]:  # 最多显示三列
                fig = Figure(figsize=(8, 4))
                canvas = FigureCanvas(fig)
                ax = fig.add_subplot(111)
                value_counts = df[col].value_counts().head(10)
                value_counts.plot(kind='bar', ax=ax)
                ax.set_title(f'{col} 分布')
                ax.tick_params(axis='x', rotation=45)
                self.chart_layout.addWidget(canvas)
        except Exception as e:
            self.text_tab.append(f"图表生成错误: {str(e)}")

    def show_message(self, message):
        """显示消息"""
        self.text_tab.clear()
        self.text_tab.append(message)
        self.tabs.setCurrentIndex(1)

    def add_row(self):
        """在表格末尾添加新行"""
        row_count = self.data_tab.rowCount()
        self.data_tab.insertRow(row_count)

    def delete_selected_rows(self):
        """删除选中的行"""
        selected_rows = set()
        for item in self.data_tab.selectedItems():
            selected_rows.add(item.row())

        # 从后往前删除，避免索引变化
        for row in sorted(selected_rows, reverse=True):
            self.data_tab.removeRow(row)

    def commit_changes(self):
        """提交更改到数据库"""
        # 实现保存更改逻辑
        QMessageBox.information(self, "提交更改", "数据更改已提交到数据库")

    def revert_changes(self):
        """撤销未提交的更改"""
        # 实现撤销逻辑
        QMessageBox.information(self, "撤销更改", "已撤销未提交的更改")

    def export_data(self):
        """导出数据"""
        # 实现导出逻辑
        QMessageBox.information(self, "导出数据", "数据导出功能将在后续版本中提供")

    def import_data(self):
        """导入数据"""
        # 实现导入逻辑
        QMessageBox.information(self, "导入数据", "数据导入功能将在后续版本中提供")